package com.unlcn.ils.wms.backend.service.inbound.impl;

import cn.huiyunche.commons.exception.BusinessException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.unlcn.ils.wms.backend.bo.inboundBO.WmsPrintBarcodeBO;
import com.unlcn.ils.wms.backend.enums.*;
import com.unlcn.ils.wms.backend.service.inbound.WmsJMInboundService;
import com.unlcn.ils.wms.backend.service.webservice.client.WmsJmDcsService;
import com.unlcn.ils.wms.backend.service.webservice.client.WmsJmSapService;
import com.unlcn.ils.wms.backend.util.BitMatrixToImageWritter;
import com.unlcn.ils.wms.backend.util.DateUtils;
import com.unlcn.ils.wms.backend.util.GenerateFlowCodeUtils;
import com.unlcn.ils.wms.backend.util.SnowflakeIdWorker;
import com.unlcn.ils.wms.backend.util.jpush.JpushClientUtils;
import com.unlcn.ils.wms.base.businessDTO.baseData.WmsEmptyLocationDTO;
import com.unlcn.ils.wms.base.businessDTO.inbound.AsnOrderDTO;
import com.unlcn.ils.wms.base.mapper.additional.WmsInboundAsnOrderAddMapper;
import com.unlcn.ils.wms.base.mapper.additional.WmsLocationExtMapper;
import com.unlcn.ils.wms.base.mapper.additional.wmsInboundPloy.*;
import com.unlcn.ils.wms.base.mapper.extmapper.WmsWarehouseNoticeExtMapper;
import com.unlcn.ils.wms.base.mapper.inbound.*;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsOutOfStorageExcpMapper;
import com.unlcn.ils.wms.base.mapper.junmadcs.WmsOutOfStorageMapper;
import com.unlcn.ils.wms.base.mapper.stock.WmsWarehouseMapper;
import com.unlcn.ils.wms.base.mapper.sys.SysUserMapper;
import com.unlcn.ils.wms.base.mapper.sys.SysUserRoleMapper;
import com.unlcn.ils.wms.base.model.inbound.*;
import com.unlcn.ils.wms.base.model.junmadcs.WmsOutOfStorage;
import com.unlcn.ils.wms.base.model.junmadcs.WmsOutOfStorageExample;
import com.unlcn.ils.wms.base.model.junmadcs.WmsOutOfStorageExcp;
import com.unlcn.ils.wms.base.model.junmadcs.WmsOutOfStorageExcpExample;
import com.unlcn.ils.wms.base.model.stock.WmsWarehouse;
import com.unlcn.ils.wms.base.model.sys.SysUser;
import com.unlcn.ils.wms.base.model.sys.SysUserRole;
import com.unlcn.ils.wms.base.model.sys.SysUserRoleExample;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 君马库入库业务
 */
@Service
public class WmsJMInboundServiceImpl implements WmsJMInboundService {

    private Logger logger = LoggerFactory.getLogger(WmsJMInboundServiceImpl.class);
    private static final String TYPE_INBOUND = "1002";//入库收货质检和入库确认推送类别
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final static String EXCEL2003L = ".xls";    //2003- 版本的excel
    private final static String EXCEL2007U = ".xlsx";   //2007+ 版本的excel

    @Autowired
    private WmsOutOfStorageMapper wmsOutOfStorageMapper;

    @Autowired
    private WmsOutOfStorageExcpMapper wmsOutOfStorageExcpMapper;

    @Autowired
    private WmsAsnTempMapper wmsAsnTempMapper;

    @Autowired
    private WmsInboundOrderMapper wmsInboundOrderMapper;

    @Autowired
    private WmsLocationExtMapper wmsLocationExtMapper;

    @Autowired
    private WmsInboundAllocationMapper wmsInboundAllocationMapper;

    @Autowired
    private WmsInboundOrderDetailMapper wmsInboundOrderDetailMapper;

    @Autowired
    private WmsInboundAsnOrderAddMapper wmsInboundAsnOrderAddMapper;

    @Autowired
    private WmsInboundPloyExtMapper wmsInboundPloyExtMapper;

    @Autowired
    private WmsInboundPloyConditionExtMapper wmsInboundPloyConditionExtMapper;

    @Autowired
    private WmsInboundPloyOperatorExtMapper wmsInboundPloyOperatorExtMapper;

    @Autowired
    private WmsInboundPloyFlowtoExtMapper wmsInboundPloyFlowtoExtMapper;

    @Autowired
    private WmsInboundPloyLocationExtMapper wmsInboundPloyLocationExtMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private WmsWarehouseMapper wmsWarehouseMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WmsJmDcsService wmsJmDcsService;

    @Autowired
    private WmsJmSapService wmsJmSapService;

    @Autowired
    private WmsWarehouseNoticeHeadMapper wmsWarehouseNoticeHeadMapper;

    @Autowired
    private WmsWarehouseNoticeDetailMapper wmsWarehouseNoticeDetailMapper;

    @Autowired
    private WmsWarehouseNoticeExtMapper wmsWarehouseNoticeExtMapper;

    /**
     * 导入excel
     *
     * @param whCode 仓库code
     * @param userId 用户id
     * @param file   文件
     */
    @Override
    public void saveImportAsnByExcel(String whCode, String userId, MultipartFile file) throws Exception {
        logger.info("WmsJMInboundServiceImpl.saveImportAsnByExcelOld param.{},{},{}", whCode, userId, file);
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库Code为空!");
        }
        if (Objects.equals(file, null) || file.isEmpty()) {
            throw new BusinessException("请选择要上传的数据记录");
        }
        //查询用户
        SysUser sysUser = null;
        if (StringUtils.isNotBlank(userId)) {
            sysUser = sysUserMapper.selectByPrimaryKey(Integer.valueOf(userId));
        }
        //查上一次的批次号
        WmsWarehouseNoticeHeadExample headExample = new WmsWarehouseNoticeHeadExample();
        headExample.createCriteria().andWnhBatchNoIsNotNull();
        headExample.setOrderByClause("wnh_create desc");
        headExample.setLimitStart(0);
        headExample.setLimitEnd(1);
        List<WmsWarehouseNoticeHead> noticeHeads = wmsWarehouseNoticeHeadMapper.selectByExample(headExample);
        String atBatchNo;
        if (CollectionUtils.isNotEmpty(noticeHeads)) {
            atBatchNo = noticeHeads.get(0).getWnhBatchNo();
            atBatchNo = GenerateFlowCodeUtils.getnumber("BTN", atBatchNo, "0000");
        } else {
            atBatchNo = GenerateFlowCodeUtils.getnumber("BTN", null, "0000");
        }
        //解析excel并把数据封装到asn列表
        saveImportExcelToAsn(whCode, sysUser, file, atBatchNo);
    }


    /**
     * 导入excel
     *
     * @param whCode 仓库code
     * @param userId 用户id
     * @param file   文件
     */
    @Override
    public void saveImportAsnByExcelOld(String whCode, String userId, MultipartFile file) throws Exception {
        logger.info("WmsJMInboundServiceImpl.saveImportAsnByExcelOld param.{},{},{}", whCode, userId, file);
        if (StringUtils.isBlank(whCode)) {
            throw new BusinessException("仓库Code为空!");
        }
        //if (StringUtils.isBlank(userId))
        //    throw new BusinessException("用户Id不能为空!");
        if (Objects.equals(file, null) || file.isEmpty()) {
            throw new BusinessException("请选择要上传的数据记录");
        }
        //查询用户
        SysUser sysUser = null;
        if (StringUtils.isNotBlank(userId)) {
            sysUser = sysUserMapper.selectByPrimaryKey(Integer.valueOf(userId));
        }
        //if (Objects.equals(sysUser, null))
        //    throw new BusinessException("未查询到对应用户信息");
        //查上一次的批次号
        WmsAsnTempExample asnTempExample = new WmsAsnTempExample();
        asnTempExample.setLimitStart(0);
        asnTempExample.setLimitEnd(1);
        asnTempExample.setOrderByClause("gmt_create desc");
        List<WmsAsnTemp> wmsAsnTemps = wmsAsnTempMapper.selectByExample(asnTempExample);

        String atBatchNo = null;
        if (CollectionUtils.isNotEmpty(wmsAsnTemps)) {
            atBatchNo = wmsAsnTemps.get(0).getAtBatchNo();
            atBatchNo = GenerateFlowCodeUtils.getnumber("BTN", atBatchNo, "0000");
        } else {
            atBatchNo = GenerateFlowCodeUtils.getnumber("BTN", null, "0000");
        }
        //解析excel并把数据封装到asn列表
        saveImportExcelToAsnOld(whCode, sysUser, file, atBatchNo);
    }

    /**
     * asn打印功能
     * <p>
     * 2018-4-23 重构入库通知单  此方法新方法
     * </p>
     *
     * @param whCode 仓库code
     * @param atId   参数id
     */
    @Override
    public ArrayList<Object> getAsnQrCode(String whCode, String[] atId) {
        logger.info("WmsJMInboundServiceImpl.getAsnQrCode param.{},{}", whCode, atId);
        if (Objects.equals(atId, null)) {
            throw new BusinessException("请选择要打印的数据!");
        }
        ArrayList<Object> result = Lists.newArrayList();
        List<String> ids = Arrays.asList(atId);
        List<WmsWarehouseNoticeDetail> details = wmsWarehouseNoticeExtMapper.selectNoticeListByIdsForPrint(ids);
        if (CollectionUtils.isEmpty(details)) {
            throw new BusinessException("未查询到对应的通知单信息");
        }
        details.forEach(v -> {
            try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                WmsPrintBarcodeBO barcodeBO = new WmsPrintBarcodeBO();
                BufferedImage qrImageBuffer = BitMatrixToImageWritter.createQRImageBuffer(v.getWndVin(), 300, 300);
                ImageIO.write(qrImageBuffer, "png", byteArrayOutputStream);
                Base64 base64 = new Base64();
                String base64Img = base64.encodeToString(byteArrayOutputStream.toByteArray());
                //BASE64Encoder base64 = new BASE64Encoder();
                //String base64Img = base64.encode(byteArrayOutputStream.toByteArray());
                barcodeBO.setBarcode(base64Img);//设置属性值返回前台页面
                barcodeBO.setVin(v.getWndVin());
                result.add(barcodeBO);
            } catch (IOException ie) {
                logger.error("WmsJMInboundServiceImpl.getAsnQrCode  IOException:", ie);
                throw new BusinessException("生成二维码异常");
            } catch (Exception e) {
                logger.error("WmsJMInboundServiceImpl.getAsnQrCode  Exception:", e);
                throw new BusinessException("入库通知单打印异常");
            }
        });
        return result;
    }

    /**
     * asn打印功能
     * <p>
     * 2018-4-23 重构入库通知单  此方法重写，新方法{@link WmsJMInboundServiceImpl#getAsnQrCodeOld}
     * </p>
     *
     * @param whCode 仓库code
     * @param atId   参数id
     * @throws Exception 异常
     */
    @Override
    @Deprecated
    public ArrayList<Object> getAsnQrCodeOld(String whCode, String[] atId) throws Exception {
        logger.info("WmsJMInboundServiceImpl.saveImportAsnByExcelOld param.{},{},{}", whCode, atId);
        if (Objects.equals(atId, null)) {
            throw new BusinessException("请选择要打印的数据!");
        }
        ArrayList<Object> result = Lists.newArrayList();
        for (String id : atId) {
            WmsAsnTemp asnTemp = wmsAsnTempMapper.selectByPrimaryKey(Long.valueOf(id));
            if (Objects.equals(asnTemp, null)) {
                throw new BusinessException("未查询到对应的asn数据!");
            }
            ByteArrayOutputStream byteArrayOutputStream = null;
            WmsPrintBarcodeBO barcodeBO = new WmsPrintBarcodeBO();
            //打印
            try {
                if (StringUtils.isBlank(asnTemp.getAtVin())) {
                    throw new BusinessException("未查询到Id为" + id + "的车架号");
                }
                BufferedImage qrImageBuffer = BitMatrixToImageWritter.createQRImageBuffer(asnTemp.getAtVin(), 300, 300);
                byteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(qrImageBuffer, "png", byteArrayOutputStream);
                //Base64 base64 = new Base64();
                String base64Img = new Base64().encodeToString(byteArrayOutputStream.toByteArray());
                //BASE64Encoder base64 = new BASE64Encoder();
                //String base64Img = base64.encode(byteArrayOutputStream.toByteArray());
                barcodeBO.setBarcode(base64Img);//设置属性值返回前台页面
                barcodeBO.setVin(asnTemp.getAtVin());
            } catch (Exception e) {
                logger.error("WmsJMInboundServiceImpl.saveImportAsnByExcelOld param.{},{},{}", e);
                throw new BusinessException(e.getMessage());
            } finally {
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
            }
            result.add(barcodeBO);
        }
        return result;
    }

    /**
     * 质检收货/分配库位/推送库位到app/并调用sap退车申请;
     *
     * @param vin        车架号
     * @param userId_str 用户id
     */
    @Override
    public AsnOrderDTO saveAllcationByExtra(String vin, String userId_str) throws Exception {
        logger.info("WmsJMInboundServiceImpl.saveAllcationByExtra param.{},{},{}", vin, userId_str);
        //因为分为手动输入和扫码输入;需要根据长度判断是否输入的车架号
        if (StringUtils.isBlank(vin)) {
            throw new BusinessException("输入信息不能为空!");
        }
        if (StringUtils.isBlank(userId_str)) {
            throw new BusinessException("用户ID不能为空!");
        }
        int userId = Integer.parseInt(userId_str);
        //判断手动输入的是车架号还是运单号
        if (vin.trim().length() != 17) {
            //车架号实际是运单号(只是参数名为vin)
            WmsInboundOrderExample orderExample = new WmsInboundOrderExample();
            WmsInboundOrderExample.Criteria criteria = orderExample.createCriteria();
            criteria.andOdWaybillNoEqualTo(vin);
            criteria.andIsDeletedNotEqualTo(DeleteFlagEnum.DELETED.getValue());
            List<WmsInboundOrder> wmsInboundOrders = wmsInboundOrderMapper.selectByExample(orderExample);
            if (CollectionUtils.isEmpty(wmsInboundOrders)) {
                throw new BusinessException("未查询到对应的运单号的入库信息");
            }
            //查出运单号对应的车架号
            Long odId = wmsInboundOrders.get(0).getOdId();
            WmsInboundOrderDetailExample detailExample = new WmsInboundOrderDetailExample();
            WmsInboundOrderDetailExample.Criteria detailExampleCriteria = detailExample.createCriteria();
            detailExampleCriteria.andOddOdIdEqualTo(odId);
            List<WmsInboundOrderDetail> wmsInboundOrderDetails = wmsInboundOrderDetailMapper.selectByExample(detailExample);
            if (CollectionUtils.isEmpty(wmsInboundOrderDetails)) {
                throw new BusinessException("未查询到对应的运单号的车架号信息");
            }
            vin = wmsInboundOrderDetails.get(0).getOddVin();
        }


        //通过vin得到入库基本信息

        AsnOrderDTO asnOrderDTO = wmsInboundAsnOrderAddMapper.queryByVin(vin);
        if (asnOrderDTO == null) {
            throw new BusinessException("车架号不正确，请确认是否有此车架号：" + vin);
        } else if (asnOrderDTO.getOdStatus().equals(String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_WAIT_INBOUND.getValue()))) {
            throw new BusinessException("此车架号" + vin + "已收货，不允许再次收货");
        } else if (asnOrderDTO.getOdStatus().equals(String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_FINISH.getValue()))) {
            throw new BusinessException("此车架号" + vin + "已入库，不允许再次收货");
        }

        //通过找到仓库code

        SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
        sysUserRoleExample.createCriteria().andUserIdEqualTo(userId);
        List<SysUserRole> sysUserRole = sysUserRoleMapper.selectByExample(sysUserRoleExample);
        WmsWarehouse wmsWarehouse = wmsWarehouseMapper.selectByPrimaryKey(sysUserRole.get(0).getWarehouseId());
        List<WmsInboundPloy> wmsInboundPloyList = wmsInboundPloyExtMapper.getPloyList(wmsWarehouse.getWhCode());
        //根据策略code查询策略条件
        Map<String, String> resultLocationMap = Maps.newHashMap();

        //查询所有空库位
        Map<String, Object> queryMap = Maps.newHashMap();
        Map<String, List<WmsEmptyLocationDTO>> zoneMap = Maps.newHashMap();//根据库区维度进行存放
        queryMap.put("whCode", wmsWarehouse.getWhCode());
        List<com.unlcn.ils.wms.base.businessDTO.baseData.WmsEmptyLocationDTO> locationList = wmsLocationExtMapper.getWmsEmptyLocation(queryMap);
        if (CollectionUtils.isEmpty(locationList) && locationList.size() <= 0) {
            throw new BusinessException("仓库没有了空库位，请联系IT人员。");
        }

        if (CollectionUtils.isNotEmpty(locationList) && locationList.size() > 0) {
            for (WmsEmptyLocationDTO wmsEmptyLocationDTO : locationList) {
                if (zoneMap.containsKey(wmsEmptyLocationDTO.getLocZoneCode())) {
                    List<WmsEmptyLocationDTO> zlist = zoneMap.get(wmsEmptyLocationDTO.getLocZoneCode());
                    zlist.add(wmsEmptyLocationDTO);
                    zoneMap.put(wmsEmptyLocationDTO.getLocZoneCode(), zlist);
                } else {
                    List<WmsEmptyLocationDTO> userList = Lists.newArrayList();
                    userList.add(wmsEmptyLocationDTO);
                    zoneMap.put(wmsEmptyLocationDTO.getLocZoneCode(), userList);
                }
            }
        }

        /*Map<String,Map<String,Map<String,Object>>> map = Maps.newConcurrentMap();//所有策略信息
        Map<String,Object> conditionMap = Maps.newConcurrentMap();//条件
        Map<String,Object> flowtoMap = Maps.newConcurrentMap();//流向
        Map<Long,Object> locationMap = Maps.newConcurrentMap();//库区库位*/
        /**
         * 查询库区库位
         */
        Map<String, List<WmsEmptyLocationDTO>> havaLocation = Maps.newHashMap();//得到空库位
        if (wmsInboundPloyList.size() > 0) {
            List<WmsInboundPloyLocation> wmsInboundPloyLocationList = wmsInboundPloyLocationExtMapper.getPloyLocationList(wmsInboundPloyList.get(0).getPyCode());
            if (wmsInboundPloyLocationList.size() > 0) {
                for (WmsInboundPloyLocation wmsInboundPloyLocation : wmsInboundPloyLocationList) {
                    String startRow = wmsInboundPloyLocation.getPylStartRow();//开始排
                    String endRow = wmsInboundPloyLocation.getPylEndRow();//结束排
                    List<WmsEmptyLocationDTO> list = zoneMap.get(wmsInboundPloyLocation.getPylZoneCode());//根据策略库区得到空库位
                    List<WmsEmptyLocationDTO> getLocationListStr = getLoationList(list, Long.valueOf(startRow), Long.valueOf(endRow));
                    havaLocation.put(wmsInboundPloyLocation.getPylZoneCode(), getLocationListStr);
                }
            }
        }

        //已经被占用的库位，在第二次循环的时候需要去掉此list的库位。

        List<String> occupyList = Lists.newArrayList();


        //循环被自动分配的订单

        //for(WmsAllocationBO wmsAllocationBO : wmsAllocationVOList) {
        String customerCode = asnOrderDTO.getOdCustomerCode();//货主
        String vehicleSpecCode = asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddVehicleSpecCode();//车型
        WmsInboundOrder wmsInboundOrder = wmsInboundOrderMapper.selectByPrimaryKey(Long.valueOf(asnOrderDTO.getOdId()));
        if (null == wmsInboundOrder) {
            Exception ex = new Exception("订单信息为空");
            throw ex;
        }
        String dest = wmsInboundOrder.getOdDest();//目的地
        String origin = wmsInboundOrder.getOdOrigin();//起始地
        /**
         * 订单能匹配上当前选择的策略，当订单匹配策略那么返回havaLocation里的库位，否则不返回让前端自己人工选择。
         */
        boolean inPloy = true;

        /**
         * 查询条件
         */
        if (wmsInboundPloyList.size() > 0) {
            List<WmsInboundPloyCondition> wmsInboundPloyConditionList = wmsInboundPloyConditionExtMapper.getPloyConditionList(wmsInboundPloyList.get(0).getPyCode());
            if (CollectionUtils.isNotEmpty(wmsInboundPloyConditionList) && wmsInboundPloyConditionList.size() > 0) {
                for (WmsInboundPloyCondition wmsInboundPloyCondition : wmsInboundPloyConditionList) {
                    List<WmsInboundPloyOperator> wmsInboundPloyOperator = wmsInboundPloyOperatorExtMapper.getOperatorByCode(wmsInboundPloyCondition.getPycOperatorCode());
                    String operatorCode = wmsInboundPloyOperator.get(0).getPyoOperatorCode();
                    String[] value = wmsInboundPloyCondition.getPycValue().split("&");

                    if ("10".equals(wmsInboundPloyCondition.getPycType())) {//货主
                        boolean flag = Arrays.asList(value).contains(customerCode);
                        /**
                         * 10为货主，判断订单是否适用于当前策略 ，不适用直接退出循环 库区库位赋值为空
                         */
                        if (!isPloy(operatorCode, flag)) {
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneCode("");
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneName("");
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocCode("");
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocName("");
                            break;
                        }
                    }
                    if ("20".equals(wmsInboundPloyCondition.getPycType())) {//车型
                        /**
                         * 20为车型，判断订单是否适用于当前策略 ，不适用直接退出循环 库区库位赋值为空
                         */
                        if (!isPloy(operatorCode, Arrays.asList(value).contains(vehicleSpecCode))) {
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneCode("");
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneName("");
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocCode("");
                            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocName("");
                            break;
                        }
                    }

                    //conditionMap.put(wmsInboundPloyCondition.getPycCode(), wmsInboundPloyCondition);
                }
            }


            /**
             * 查询流向
             */
            List<WmsInboundPloyFlowto> wmsInboundPloyFlowtoList = wmsInboundPloyFlowtoExtMapper.getPloyFlowtoList(wmsInboundPloyList.get(0).getPyCode());
            if (CollectionUtils.isNotEmpty(wmsInboundPloyFlowtoList) && wmsInboundPloyFlowtoList.size() > 0) {
                for (WmsInboundPloyFlowto wmsInboundPloyFlowto : wmsInboundPloyFlowtoList) {
                    if (wmsInboundPloyFlowto.getPyfFromCode().equals(origin) && wmsInboundPloyFlowto.getPyfToCode().equals(dest)) {
                        inPloy = true;
                    }
                }
            }

            for (Map.Entry<String, List<WmsEmptyLocationDTO>> entry : havaLocation.entrySet()) {
                List<WmsEmptyLocationDTO> valueList = entry.getValue();
                if (CollectionUtils.isEmpty(valueList)) {
                    break;
                }
                asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneCode(entry.getKey());//code跟name一样
                asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneName(entry.getKey());//code跟name一样
                for (WmsEmptyLocationDTO list : valueList) {
                    asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhCode(list.getLocWhCode());
                    asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhName(list.getLocWhName());
                    asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneCode(list.getLocZoneCode());
                    asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneName(list.getLocZoneName());
                    asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocCode(list.getLocCode());
                    asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocName(list.getLocName());
                    occupyList.add(list.getLocCode());
                    valueList.remove(list);
                    break;
                }
            }
        }
        /**
         * 当策略没有匹配到库位那么任务分配一个库区库位
         */
        if (asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneCode() == null
                || asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneCode() == null
                || asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode() == null
                || asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocName() == null) {
            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneCode(locationList.get(0).getLocZoneCode() == null ? locationList.get(0).getLocZoneName() : locationList.get(0).getLocZoneCode());
            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhZoneName(locationList.get(0).getLocZoneName() == null ? locationList.get(0).getLocZoneCode() : locationList.get(0).getLocZoneName());
            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocCode(locationList.get(0).getLocCode() == null ? locationList.get(0).getLocName() : locationList.get(0).getLocCode());
            asnOrderDTO.getAsnOrderDetailDTOList().get(0).setOddWhLocName(locationList.get(0).getLocName() == null ? locationList.get(0).getLocCode() : locationList.get(0).getLocName());
        }
        /**
         * 修改入库单为已收货待入库
         */
        WmsInboundOrder object = new WmsInboundOrder();
        object.setOdStatus(String.valueOf(WmsInboundStatusEnum.WMS_INBOUND_WAIT_INBOUND.getValue()));
        //查询用户，增加收货人字段
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        object.setOdConsigneeId(userId_str);
        object.setOdConsigneeDate(new Date());
        object.setOdConsigneeName(sysUser.getName());
        WmsInboundOrderExample wmsInboundOrderExample = new WmsInboundOrderExample();
        wmsInboundOrderExample.createCriteria().andOdIdEqualTo(Long.valueOf(asnOrderDTO.getOdId()));
        wmsInboundOrderMapper.updateByExampleSelective(object, wmsInboundOrderExample);

        /**
         * 更新order详情表
         */
        String whCode = asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhCode();
        WmsInboundOrderDetail wmsInboundOrderDetail = new WmsInboundOrderDetail();
        wmsInboundOrderDetail.setOddOdId(asnOrderDTO.getOdId());
        wmsInboundOrderDetail.setOddWhCode(whCode);
        wmsInboundOrderDetail.setOddWhName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhName());
        wmsInboundOrderDetail.setOddWhZoneCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneCode());
        wmsInboundOrderDetail.setOddWhZoneName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneName());
        wmsInboundOrderDetail.setOddWhLocCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode());
        wmsInboundOrderDetail.setOddWhLocName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocName());
        WmsInboundOrderDetailExample wmsInboundOrderDetailExample = new WmsInboundOrderDetailExample();
        wmsInboundOrderDetailExample.createCriteria().andOddOdIdEqualTo(Long.valueOf(asnOrderDTO.getOdId()));
        wmsInboundOrderDetailMapper.updateByExampleSelective(wmsInboundOrderDetail, wmsInboundOrderDetailExample);
        /**
         * 库区库位信息新增到分配表
         */
        WmsInboundAllocation wmsInboundAllocation = new WmsInboundAllocation();
        wmsInboundAllocation.setAlVin(vin);
        wmsInboundAllocation.setAlStatus(WmsInboundAllocationStatusEnum.ALLOCATED_CONFIRM.getValue());
        wmsInboundAllocation.setAlWhId(String.valueOf(wmsWarehouse.getWhId()));
        wmsInboundAllocation.setAlSourceZoneCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneCode());
        wmsInboundAllocation.setAlSourceZoneName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhZoneName());
        wmsInboundAllocation.setAlSourceLocCode(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocCode());
        wmsInboundAllocation.setAlSourceLocName(asnOrderDTO.getAsnOrderDetailDTOList().get(0).getOddWhLocName());
        wmsInboundAllocation.setCreateUserId(String.valueOf(sysUser.getId()));
        wmsInboundAllocation.setCreateUserName(sysUser.getName());
        wmsInboundAllocation.setIsDeleted(DeleteFlagEnum.NORMAL.getValue());
        wmsInboundAllocation.setGmtCreate(new Date());
        wmsInboundAllocation.setIsDeleted((byte) 1);
        wmsInboundAllocationMapper.insert(wmsInboundAllocation);
        //}
        if (!Objects.equals(asnOrderDTO, null)) {
            //推送库位到app
            updateSendMessageToAPP(asnOrderDTO, userId_str);
        }

        /**
         * -君马需要再推送退车到sap
         */
        //if (StringUtils.isNotBlank(whCode)) {
        //    if (whCode.contains(WhCodeEnum.JM_CS.getValue().substring(0, 2))) {
        //        //君马库调用退车推送
        //        WmsDealerCarBackExample backExample = new WmsDealerCarBackExample();
        //        WmsDealerCarBackExample.Criteria criteria = backExample.createCriteria();
        //        criteria.andCbVinEqualTo(vin).andCbZstatusNotEqualTo(HandoverSendStatusEnum.SEND_SUCCESS.getStatusCode());
        //        List<WmsDealerCarBack> wmsDealerCarBacks = wmsDealerCarBackMapper.selectByExample(backExample);
        //        if (CollectionUtils.isNotEmpty(wmsDealerCarBacks)) {
        //
        //            //WmsDealerCarBack wmsDealerCarBack = wmsDealerCarBacks.get(0);
        //            //WmsDealerCarBackBO wmsDealerCarBackBO = new WmsDealerCarBackBO();
        //            //BeanUtils.copyProperties(wmsDealerCarBack, wmsDealerCarBackBO);
        //            //todo 校验结果修改状态
        //            //arrayList.add(wmsDealerCarBackBO)
        //            wmsJmSapService.updateWmsDealerCarBack(wmsDealerCarBacks);
        //        }
        //    }
        //}
        return asnOrderDTO;
    }


    /**
     * 推送库位信息给APP
     *
     * @param result 参数
     * @param userId 用户id
     */
    @Override
    public void updateSendMessageToAPP(AsnOrderDTO result, String userId) throws Exception {
        //推送消息到app
        String jsonStr = "{ \"locName\": " + result.getAsnOrderDetailDTOList().get(0).getOddWhLocName() + ", \"status\":\"20\", \"statusName\": \"已入库\" }";
        //查询移库司机id
        if (StringUtils.isBlank(result.getOdSupplierId())) {
            throw new BusinessException("该车架号:" + result.getAsnOrderDetailDTOList().get(0).getOddVin() + "未绑定移库司机");
        }
        JpushClientUtils.sendToAllAndroid(result.getOdSupplierId(), jsonStr, TYPE_INBOUND);

        String text = "{ \"vin\":\"" + result.getAsnOrderDetailDTOList().get(0).getOddVin() + "\"," +
                "{ \"zone\":\"" + result.getAsnOrderDetailDTOList().get(0).getOddWhZoneName() + "\"," +
                "{ \"location\":\"" + result.getAsnOrderDetailDTOList().get(0).getOddWhLocName() + "\",}";
        BufferedImage qrImageBuffer = BitMatrixToImageWritter.createQRImageBuffer(text, 60, 60);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(qrImageBuffer, "png", os);
        //Base64 base64 = new Base64();
        //BASE64Encoder base64 = new BASE64Encoder();
        //String base64Img = base64.encode(os.toByteArray());
        String base64Img = new Base64().encodeToString(os.toByteArray());
        result.setOdRemark(base64Img);
                /*BASE64Decoder decoder = new BASE64Decoder();
                //Base64解码
                byte[] b = decoder.decodeBuffer(base64Img);
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {// 调整异常数据
                        b[i] += 256;
                    }
                }
                String filename = System.currentTimeMillis()+"png";
                String path = "E://"+filename;
                OutputStream out = new FileOutputStream(path);
                out.write(b);

                QiniuResponseVO upload = QiniuUtil.upload(b, null);
                String key = upload.getKey();
                String downloadURL = QiniuUtil.generateDownloadURL(QiniuConstant.QINIU_DOWNLOAD_ADDRESS, key, "", null, null);
                result.setOdRemark(downloadURL);
                *//**
         * 保存key
         *//*
                wmsStrategyService.saveBarcodeKey(result.getOdId(),result.getAsnOrderDetailDTOList().get(0).getOddVin(),key);*/
                /*try {
                    DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
                    //get a printer
                    PrintService[] printers = PrintServiceLookup.lookupPrintServices(flavor, null);
                    for (int i = 0; i < printers.length; i++) System.out.println(printers[i].getName());
                    PrintService printer = printers[0];
                    //job
                    DocPrintJob job = printer.createPrintJob();
                    //document
                    BufferedImage img = new BufferedImage(400, 300, BufferedImage.TYPE_USHORT_555_RGB);
                    String text = "{ \"vin\":\"" + result.getAsnOrderDetailDTOList().get(0).getOddVin() + "\"," +
                            "{ \"zone\":\"" + result.getAsnOrderDetailDTOList().get(0).getOddWhZoneName() + "\"," +
                            "{ \"location\":\"" + result.getAsnOrderDetailDTOList().get(0).getOddWhLocName() + "\",}";
                    BufferedImage qrImageBuffer = BitMatrixToImageWritter.createQRImageBuffer(text, 30, 30);
                    Graphics g = qrImageBuffer.getGraphics();
                    //g.drawString("12345", 30, 30);
                    ByteArrayOutputStream outstream = new ByteArrayOutputStream();
                    ImageIO.write(qrImageBuffer, "jpg", outstream);

                    byte[] buf = outstream.toByteArray();
                    InputStream stream = new ByteArrayInputStream(buf);
                    Doc doc = new SimpleDoc(stream, flavor, null);
                    //print
                    job.print(doc, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("二维码打印异常");
                }*/
    }


    /**
     * 根据条件返回所需策略库位
     */
    private List<WmsEmptyLocationDTO> getLoationList(List<WmsEmptyLocationDTO> list, Long startRow, Long endRow) {
        List<WmsEmptyLocationDTO> locationList = Lists.newArrayList();
        for (WmsEmptyLocationDTO wmsEmptyLocationDTO : list) {
            String column = wmsEmptyLocationDTO.getLocName().substring(wmsEmptyLocationDTO.getLocName().indexOf("-") + 1, wmsEmptyLocationDTO.getLocName().lastIndexOf("-"));
            Long row = Long.valueOf(column);
            if (row.longValue() >= startRow.longValue() && row.longValue() <= endRow.longValue()) {
                locationList.add(wmsEmptyLocationDTO);
            }
        }
        return locationList;
    }

    /**
     * 判断订单是否适用于当前选择的策略
     * 是 true
     * 否 false
     *
     * @return
     */
    private boolean isPloy(String operatorCode, boolean flag) {
        boolean isPloy = false;
        switch (operatorCode) {
            case "10"://等于
                if (flag) {
                    isPloy = true;
                }
                break;
            case "20"://不等于
                if (flag) {
                    isPloy = false;
                } else {
                    isPloy = true;
                }
                break;
            case "30"://包含
                if (flag) {
                    isPloy = true;
                }
                break;
            case "40"://不包含
                if (flag) {
                    isPloy = false;
                } else {
                    isPloy = true;
                }
                break;
            case "50"://是
                if (flag) {
                    isPloy = true;
                }
                break;
            case "60"://不是
                if (flag) {
                    isPloy = false;
                } else {
                    isPloy = true;
                }
                break;
            case "70"://大于等于
                System.out.println("大于等于");
                break;
            case "80"://小于等于
                System.out.println("小于等于");
                break;
        }
        return isPloy;
    }

    /**
     * 解析excel数据
     * <p>
     * 2018-4-19 入库通知单重构 此方法
     * </p>
     *
     * @param whCode    仓库code
     * @param sysUser   用户
     * @param file      文件
     * @param atBatchNo 批次号
     */
    private void saveImportExcelToAsn(String whCode, SysUser sysUser, MultipartFile file, String atBatchNo) throws Exception {
        //解析excel
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        if (originalFilename.endsWith(EXCEL2003L)) {
            //解析2003excel
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            int num = workbook.getNumberOfSheets();//获取表单数
            Sheet sheet = null;
            //遍历Excel中所有的sheet
            for (int i = 0; i < num; i++) {
                sheet = workbook.getSheetAt(i);
                updateAsnTemp(whCode, sysUser, sheet, atBatchNo);
            }
            workbook.close();
            inputStream.close();
        } else if (originalFilename.endsWith(EXCEL2007U)) {
            //解析2007excel
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            int num = workbook.getNumberOfSheets(); //获取表单数
            Sheet sheet = null;
            //遍历Excel中所有的sheet
            for (int i = 0; i < num; i++) {
                sheet = workbook.getSheetAt(i);
                updateAsnTemp(whCode, sysUser, sheet, atBatchNo);
            }
            workbook.close();
            inputStream.close();
        } else {
            throw new BusinessException("请上传excel文件!");
        }
    }

    /**
     * 解析excel数据
     * <p>
     * 2018-4-19 入库通知单重构 此方法过时 {@link WmsJMInboundServiceImpl#saveImportExcelToAsn}
     * </p>
     *
     * @param whCode    仓库code
     * @param sysUser   用户
     * @param file      文件
     * @param atBatchNo 批次号
     */
    @Deprecated
    private void saveImportExcelToAsnOld(String whCode, SysUser sysUser, MultipartFile file, String atBatchNo) throws Exception {
        //解析excel
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        if (originalFilename.endsWith(EXCEL2003L)) {
            //解析2003excel
            HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
            int num = workbook.getNumberOfSheets();//获取表单数
            Sheet sheet = null;
            //遍历Excel中所有的sheet
            for (int i = 0; i < num; i++) {
                sheet = workbook.getSheetAt(i);
                //updateAsnTempOld(whCode, sysUser, sheet, atBatchNo);
            }
            workbook.close();
            inputStream.close();
        } else if (originalFilename.endsWith(EXCEL2007U)) {
            //解析2007excel
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            int num = workbook.getNumberOfSheets(); //获取表单数
            Sheet sheet = null;
            //遍历Excel中所有的sheet
            for (int i = 0; i < num; i++) {
                sheet = workbook.getSheetAt(i);
                //updateAsnTempOld(whCode, sysUser, sheet, atBatchNo);
            }
            workbook.close();
            inputStream.close();
        } else {
            throw new BusinessException("请上传excel文件!");
        }
    }


    /**
     * 封装每一列数据到asnTemp对象中
     * <p>
     * 2018-4-19 此方法过时
     * </p>
     *
     * @param whCode  仓库code
     * @param sysUser 用户
     * @param sheet   sheet页
     * @param batchNo 当批插入的批次号
     */
    private void updateAsnTemp(String whCode, SysUser sysUser, Sheet sheet, String batchNo) throws Exception {
        Row row;
        Cell cell;
        if (Objects.equals(sheet, null)) {
            return;
        }
        //遍历当前sheet中的所有行
        int lastRowNum = sheet.getLastRowNum();
        int firstRowNum = sheet.getFirstRowNum();
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(31L, 31L);
        ArrayList<WmsWarehouseNoticeHead> insertHeads = Lists.newArrayList();
        HashMap<String, String> lastFlowCodeMap = Maps.newHashMap();
        ArrayList<WmsWarehouseNoticeDetail> insertDetails = Lists.newArrayList();
        for (int j = firstRowNum; j <= lastRowNum; j++) {
            row = sheet.getRow(j);
            if (j == 0) {
                //跳过首行空行
                continue;
            }
            if (isBlankRow(row)) {
                //跳过
                continue;
            }
            WmsWarehouseNoticeHead head = new WmsWarehouseNoticeHead();
            WmsWarehouseNoticeDetail detail = new WmsWarehouseNoticeDetail();
            for (int y = row.getFirstCellNum(); y <= row.getLastCellNum(); y++) {
                //将数据存到对象的中
                //车架号*	物料编码*	物料名称	颜色代码	颜色名称	生产日期*	发动机号	合格证	下线日期*	变速箱号
                cell = row.getCell(y);
                switch (y) {
                    //第一个值 车架号*
                    case 0: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            detail.setWndVin(getCellValue(cell).toString());
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,车架号为空!");
                        }
                        break;
                    }
                    //第二个值 物料编码*
                    case 1: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            String materialCode = getCellValue(cell).toString();
                            String vehicleCode = materialCode.split("-")[0];
                            detail.setWndVehicleCode(vehicleCode);
                            detail.setWndVehicleName(vehicleCode);//冗余车型code  因后期匹配车的时候按照ordername起始数据
                            detail.setWndMaterialCode(getCellValue(cell).toString());
                            detail.setWndColorCode(materialCode.substring(materialCode.length() - 2,
                                    materialCode.length() - 1));
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,物料编码为空!");
                        }
                        break;
                    }
                    //第三个值 物料名称
                    case 2: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            detail.setWndMaterialName(getCellValue(cell).toString());
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,物料名称为空!");
                        }
                        break;
                    }
                    //第四个值 颜色代码--截取物料代码最后第二位(导入的时候为空)
                    case 3: {
                        //if (!Objects.equals(getCellValue(cell), null)) {
                        //    asnTemp.setAtCarColourCode(getCellValue(cell).toString());
                        //}
                        break;
                    }
                    //第四个值 颜色名称
                    case 4: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            detail.setWndColorName(getCellValue(cell).toString());
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,颜色名称为空!");
                        }
                        break;
                    }
                    //第四个值 生产日期*
                    case 5: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                                //直接转为日期格式
                                detail.setWndProducteTime(cell.getDateCellValue());
                            } else if (cell.getCellTypeEnum() == CellType.STRING) {
                                try {
                                    detail.setWndProducteTime(sdf.parse(cell.getStringCellValue()));
                                } catch (ParseException e) {
                                    throw new BusinessException("excel表中第" + j + "行,日期格式不正确(YYYY/MM/DD 或者yyyy-MM-dd HH:mm:ss)!");
                                }
                            }
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,生产日期为空!");
                        }
                        break;
                    }
                    //第四个值 发动机号
                    case 6: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            detail.setWndEngineNo(getCellValue(cell).toString());
                        }
                        break;
                    }
                    //第四个值 合格证
                    case 7: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            detail.setWndCertification(getCellValue(cell).toString());
                        }
                        break;
                    }
                    //第四个值 下线日期*
                    case 8: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                                //直接转为日期格式
                                detail.setWndOfflineTime(cell.getDateCellValue());
                            } else if (cell.getCellTypeEnum() == CellType.STRING) {
                                detail.setWndOfflineTime(sdf.parse(cell.getStringCellValue()));
                            }
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,生产日期为空!");
                        }
                        break;
                    }
                    //第四个值 变速箱号
                    case 9: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            detail.setWndGearBoxNo(getCellValue(cell).toString());
                        }
                        break;
                    }
                    default:
                        break;
                }

            }
            //重复校验
            WmsWarehouseNoticeDetailExample detailExample = new WmsWarehouseNoticeDetailExample();
            detailExample.createCriteria()
                    .andWndVinEqualTo(detail.getWndVin())
                    .andWndWarehouseCodeEqualTo(whCode)
                    .andWndDataStatusEqualTo(String.valueOf(DeleteFlagEnum.NORMAL.getValue()))
                    .andWndBusinessTypeEqualTo(InboundOrderBusinessTypeEnum.Z1.getCode());
            int i = wmsWarehouseNoticeDetailMapper.countByExample(detailExample);
            if (i > 0) {
                throw new BusinessException("该车架号:" + detail.getWndVin() + "已经存在,无需重复导入");
            }
            //补全其他字段 -detail
            detail.setWndWarehouseCode(whCode);
            detail.setWndCreate(new Date());
            detail.setWndUpdate(new Date());
            detail.setWndSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));
            detail.setWndBusinessStatus(WmsBusinessStatusEnum.WND_NOT_RECEIVE.getCode());
            detail.setWndDataStatus(String.valueOf(DeleteFlagEnum.NORMAL.getValue()));
            detail.setWndTransferFlag(WmsInboundOrderStockTransferEnum.STOCK_NORMAL.getCode());
            detail.setWndBusinessType(InboundOrderBusinessTypeEnum.Z1.getCode());
            //head
            head.setWnhId(idWorker.nextId());
            head.setWnhCustomerCode(WmsCustomerEnum.JM.getCode());
            head.setWnhCustomerName(WmsCustomerEnum.JM.getName());
            head.setWnhDataStatus(String.valueOf(DeleteFlagEnum.NORMAL.getValue()));
            head.setWnhBusinessStatus(WmsBusinessStatusEnum.WNH_NOT_INBOUND.getCode());
            head.setWnhSysSource(WmsSysSourceEnum.IMPORT.getValue());
            head.setWnhBatchNo(batchNo);
            head.setWnhDataTimestamp(Long.valueOf(DateUtils.getStringFromDate(new Date(), DateUtils.FORMAT_DATETIME_NO_SEPARATOR)));
            head.setWnhCreate(new Date());
            head.setWnhUpdate(new Date());
            head.setWnhInboundNum(1);
            head.setWnhWarehouseCode(whCode);
            if (sysUser != null) {
                head.setWnhCreateUserId(sysUser.getId());
                head.setWnhCreateUserName(sysUser.getName());
                detail.setWndCreateUserId(sysUser.getId());
                detail.setWndCreateUserName(sysUser.getName());
            } else {
                head.setWnhCreateUserName(WmsSysSourceEnum.IMPORT.getValue());
                detail.setWndCreateUserName(WmsSysSourceEnum.IMPORT.getValue());
            }
            if (sysUser != null) {
                head.setWnhUpdateUserId(sysUser.getId());
                head.setWnhUpdateUserName(sysUser.getName());
                detail.setWndUpdateUserId(sysUser.getId());
                detail.setWndUpdateUserName(sysUser.getName());
            } else {
                head.setWnhUpdateUserName(WmsSysSourceEnum.IMPORT.getValue());
                detail.setWndUpdateUserName(WmsSysSourceEnum.IMPORT.getValue());
            }

            //设置head订单流水号
            String last_code = lastFlowCodeMap.get("LAST_CODE");
            String curr_code;
            if (StringUtils.isBlank(last_code)) {
                //查数据库
                WmsWarehouseNoticeHeadExample headExample = new WmsWarehouseNoticeHeadExample();
                headExample.setLimitStart(0);
                headExample.setLimitEnd(1);
                headExample.setOrderByClause("wnh_create desc");
                List<WmsWarehouseNoticeHead> heads = wmsWarehouseNoticeHeadMapper.selectByExample(headExample);
                if (CollectionUtils.isEmpty(heads)) {
                    //
                    curr_code = GenerateFlowCodeUtils.getnumber("ASN", null, "0000");
                    lastFlowCodeMap.put("LAST_CODE", curr_code);
                } else {
                    String last_orderno = heads.get(0).getWnhUnlcnOrderNo();
                    curr_code = GenerateFlowCodeUtils.getnumber("ASN", last_orderno, "0000");
                    lastFlowCodeMap.put("LAST_CODE", curr_code);
                }
            } else {
                curr_code = GenerateFlowCodeUtils.getnumber("ASN", last_code, "0000");
                lastFlowCodeMap.put("LAST_CODE", curr_code);
            }
            head.setWnhUnlcnOrderNo(curr_code);
            //detail关联
            detail.setWndHeadId(head.getWnhId());
            //批量写入
            insertHeads.add(head);
            insertDetails.add(detail);
        }
        wmsWarehouseNoticeExtMapper.insertHeadBatch(insertHeads);
        wmsWarehouseNoticeExtMapper.insertDetailBatch(insertDetails);
    }

    /**
     * 封装每一列数据到asnTemp对象中
     * <p>
     * 2018-4-19 此方法过时
     * </p>
     *
     * @param whCode  仓库code
     * @param sysUser 用户
     * @param sheet   sheet页
     * @param batchNo 当批插入的批次号
     */
    @Deprecated
    private void updateAsnTempOld(String whCode, SysUser sysUser, Sheet sheet, String batchNo) throws Exception {
        Row row;
        Cell cell;
        if (Objects.equals(sheet, null)) {
            return;
        }
        //遍历当前sheet中的所有行
        int lastRowNum = sheet.getLastRowNum();
        int firstRowNum = sheet.getFirstRowNum();
        for (int j = firstRowNum; j <= lastRowNum; j++) {
            row = sheet.getRow(j);
            if (j == 0) {
                //跳过首行空行
                continue;
            }
            if (isBlankRow(row)) {
                //跳过
                continue;
            }

            WmsAsnTemp asnTemp = new WmsAsnTemp();
            for (int y = row.getFirstCellNum(); y <= row.getLastCellNum(); y++) {
                //将数据存到对象的中
                //车架号*	物料编码*	物料名称	颜色代码	颜色名称	生产日期*	发动机号	合格证	下线日期*	变速箱号
                cell = row.getCell(y);
                switch (y) {
                    //第一个值 车架号*
                    case 0: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            asnTemp.setAtVin(getCellValue(cell).toString());
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,车架号为空!");
                        }
                        break;
                    }
                    //第二个值 物料编码*
                    case 1: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            String atMaterialcode = getCellValue(cell).toString();
                            String[] atMaterialCodes = atMaterialcode.split("-");
                            String atVehicleCode = atMaterialCodes[0];
                            asnTemp.setAtVehicleName(atVehicleCode);
                            asnTemp.setAtMaterialCode(getCellValue(cell).toString());
                            asnTemp.setAtCarColourCode(
                                    atMaterialcode.substring(atMaterialcode.length() - 2, atMaterialcode.length() - 1));
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,物料编码为空!");
                        }
                        break;
                    }
                    //第三个值 物料名称
                    case 2: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            asnTemp.setAtMaterialName(getCellValue(cell).toString());
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,物料名称为空!");
                        }
                        break;
                    }
                    //第四个值 颜色代码--截取物料代码最后第二位(导入的时候为空)
                    case 3: {
                        //if (!Objects.equals(getCellValue(cell), null)) {
                        //    asnTemp.setAtCarColourCode(getCellValue(cell).toString());
                        //}
                        break;
                    }
                    //第四个值 颜色名称
                    case 4: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            asnTemp.setAtCarColour(getCellValue(cell).toString());
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,颜色名称为空!");
                        }
                        break;
                    }
                    //第四个值 生产日期*
                    case 5: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                                //直接转为日期格式
                                asnTemp.setAtProductionDate(cell.getDateCellValue());
                            } else if (cell.getCellTypeEnum() == CellType.STRING) {
                                try {
                                    asnTemp.setAtProductionDate(sdf.parse(cell.getStringCellValue()));
                                } catch (ParseException e) {
                                    throw new BusinessException("excel表中第" + j + "行,日期格式不正确(YYYY/MM/DD 或者yyyy-MM-dd HH:mm:ss)!");
                                }
                            }
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,生产日期为空!");
                        }
                        break;
                    }
                    //第四个值 发动机号
                    case 6: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            asnTemp.setAtEngineNumber(getCellValue(cell).toString());
                        }
                        break;
                    }
                    //第四个值 合格证
                    case 7: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            asnTemp.setAtCertification(getCellValue(cell).toString());
                        }
                        break;
                    }
                    //第四个值 下线日期*
                    case 8: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                                //直接转为日期格式
                                asnTemp.setAtOfflineDate(cell.getDateCellValue());
                            } else if (cell.getCellTypeEnum() == CellType.STRING) {
                                asnTemp.setAtOfflineDate(sdf.parse(cell.getStringCellValue()));
                            }
                        } else {
                            throw new BusinessException("excel表中第" + j + "行,生产日期为空!");
                        }
                        break;
                    }
                    //第四个值 变速箱号
                    case 9: {
                        if (!Objects.equals(getCellValue(cell), null)) {
                            asnTemp.setAtGearboxNumber(getCellValue(cell).toString());
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
            saveAsnTempOld(whCode, sysUser, batchNo, asnTemp);
        }
    }

    /**
     * 判断excel 空行
     */
    private boolean isBlankRow(Row row) {
        if (row == null)
            return true;
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (!isBlankCell(cell))
                return false;
        }
        return true;
    }

    /**
     * 判断excel 空单元格
     */
    private boolean isBlankCell(Cell hcell) {
        if (hcell == null)
            return true;
        hcell.setCellType(hcell.CELL_TYPE_STRING);
        String content = getCellValue(hcell).toString();
        return content == null || "".equals(content);
    }


    /**
     * @param whCode          仓库code
     * @param sysUser         用户
     * @param batchNo         批次号
     * @param head            head
     * @param detail          detail
     * @param idWorker        id生成
     * @param lastFlowCodeMap 存储上已流水号
     * @param insertHeads     插入的头
     * @param insertDetails   插入的明细
     */
    private void saveNoticeHeadAndDetail(String whCode,
                                         SysUser sysUser,
                                         String batchNo,
                                         WmsWarehouseNoticeHead head,
                                         WmsWarehouseNoticeDetail detail,
                                         SnowflakeIdWorker idWorker,
                                         HashMap<String, String> lastFlowCodeMap,
                                         ArrayList<WmsWarehouseNoticeHead> insertHeads,
                                         ArrayList<WmsWarehouseNoticeDetail> insertDetails) {

    }

    /**
     * 保存asn单
     *
     * @param whCode  仓库code
     * @param sysUser 用户
     * @param batchNo 批次号
     * @param asnTemp asn对象
     */
    private void saveAsnTempOld(String whCode, SysUser sysUser, String batchNo, WmsAsnTemp asnTemp) {
        //补全其他字段
        asnTemp.setWhcode(whCode);
        asnTemp.setGmtCreate(new Date());
        asnTemp.setGmtUpdate(new Date());
        asnTemp.setAtCustomerName(WmsCustomerEnum.JM.getName());
        if (!Objects.equals(sysUser, null)) {
            asnTemp.setCreateUserName(sysUser.getName());
            asnTemp.setModifyUserName(sysUser.getName());
        }
        asnTemp.setAtSendBusinessFlag(String.valueOf(SendBusinessFlagEnum.SEND_N.getValue()));//设置未同步到业务表
        asnTemp.setAtSysSource(WmsSysSourceEnum.DCS_IMPORT.getValue());//设置系统来源
        //先查出上一单的流水号
        WmsAsnTempExample asnTempExample = new WmsAsnTempExample();
        asnTempExample.setLimitStart(0);
        asnTempExample.setLimitEnd(1);
        asnTempExample.setOrderByClause("gmt_create desc, at_id desc ");
        List<WmsAsnTemp> wmsAsnTemps = wmsAsnTempMapper.selectByExample(asnTempExample);
        if (CollectionUtils.isNotEmpty(wmsAsnTemps)) {
            String lastOrderNo = wmsAsnTemps.get(0).getAtOrderNo();
            String getnumber = GenerateFlowCodeUtils.getnumber("ASN", lastOrderNo, "0000");
            asnTemp.setAtOrderNo(getnumber);
        } else {
            String getnumber = GenerateFlowCodeUtils.getnumber("ASN", null, "0000");
            asnTemp.setAtOrderNo(getnumber);
        }
        asnTemp.setAtBatchNo(batchNo);
        //重复校验
        //重复性校验
        WmsAsnTempExample example = new WmsAsnTempExample();
        WmsAsnTempExample.Criteria criteria = example.createCriteria();
        criteria.andAtVinEqualTo(asnTemp.getAtVin());
        List<WmsAsnTemp> asnTemps = wmsAsnTempMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(asnTemps)) {
            throw new BusinessException("该订单:" + asnTemp.getAtVin() + "已经存在!");
        }
        //写入数据；
        wmsAsnTempMapper.insertSelective(asnTemp);
    }

    /**
     * 描述：对表格中数值进行格式化
     */
    private Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("0");  //格式化number String字符
        DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字
        if (!Objects.equals(cell, null)) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    value = cell.getRichStringCellValue().getString();
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                        value = df.format(cell.getNumericCellValue());
                    } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                        value = sdf.format(cell.getDateCellValue());
                    } else {
                        value = df2.format(cell.getNumericCellValue());
                    }
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    value = cell.getBooleanCellValue();
                    break;
                //case Cell.CELL_TYPE_BLANK:
                //    value = "";
                //    break;
                default:
                    break;
            }
        }

        return value;
    }


    /**
     * 定时任务调用出入库接口表数据
     *
     * @throws Exception
     */
    @Override
    public void updateOutOfStorageDcs() throws Exception {
        logger.info("WmsJMInboundServiceImpl.updateOutOfStorageDcs param.{}");
        //1.查询出入库日志表中未处理的数据
        WmsOutOfStorageExample dcsStorage = new WmsOutOfStorageExample();
        dcsStorage.createCriteria().andSendStatusEqualTo(SendStatusEnum.SEND_INIT.getValue());
        dcsStorage.setOrderByClause("DATA_ID asc");
        dcsStorage.setLimitStart(0);
        dcsStorage.setLimitEnd(15);
        List<WmsOutOfStorage> outOfStorages = wmsOutOfStorageMapper.selectByExample(dcsStorage);
        if (CollectionUtils.isNotEmpty(outOfStorages)) {
            wmsJmDcsService.updateSendInOrOutboundRequest(outOfStorages);
        }
    }

    @Override
    public void updateOutOfStorageSap() throws Exception {
        //1.查询出入库日志表中未处理的数据
        WmsOutOfStorageExample sapStorage = new WmsOutOfStorageExample();
        sapStorage.createCriteria().andSendStatusSapEqualTo(SendStatusEnum.SEND_INIT.getValue());
        sapStorage.setOrderByClause("DATA_ID asc");
        sapStorage.setLimitStart(0);
        sapStorage.setLimitEnd(15);
        List<WmsOutOfStorage> sapStorages = wmsOutOfStorageMapper.selectByExample(sapStorage);
        if (CollectionUtils.isNotEmpty(sapStorages)) {
            wmsJmSapService.updateSendInOrOutbounRequest(sapStorages);
        }
    }

    /**
     * 因入库通知单重构,同步wms_asn_temp表中数据到入库通知单表中
     */
    @Override
    public void updateSyncWmsAsnTempToNotice() {
        if (logger.isInfoEnabled()) {
            logger.info("同步入库通知单表--->start");
        }
        wmsWarehouseNoticeExtMapper.updateSetMaxSQLPacket();
        int count = wmsWarehouseNoticeExtMapper.countWmsAsnTemp();
        int cy = count / 500;
        int de = count % 500;
        HashMap<String, Object> params = Maps.newHashMap();
        if (cy > 0) {
            for (int n = 0; n < cy; n++) {
                int start = n * 500;
                int end = 500;
                params.put("start", start);
                params.put("end", end);
                List<WmsAsnTemp> temps = wmsWarehouseNoticeExtMapper.selectWmsAsnTempListForSync(params);
                sysncTemps(temps);
                if (n == cy - 1) {
                    start = cy * 500;
                    end = de;
                    params.put("start", start);
                    params.put("end", end);
                    List<WmsAsnTemp> lastTemps = wmsWarehouseNoticeExtMapper.selectWmsAsnTempListForSync(params);
                    sysncTemps(lastTemps);
                }
            }
        } else {
            int start = 0;
            params.put("start", start);
            params.put("end", de);
            List<WmsAsnTemp> temps = wmsWarehouseNoticeExtMapper.selectWmsAsnTempListForSync(params);
            sysncTemps(temps);
        }
        // --test --
        //HashMap<String, Object> params = Maps.newHashMap();
        //int start = 0;
        //int end = 5;
        //params.put("start", start);
        //params.put("end", end);
        //List<WmsAsnTemp> temps = wmsWarehouseNoticeExtMapper.selectWmsAsnTempListForSync(params);
        //sysncTemps(temps);
    }


    /**
     * 因入库通知单重构,同步wms_asn_temp表中数据到入库通知单表中
     */
    @Override
    public void updateSyncTmsOrderToNotice() {
        if (logger.isInfoEnabled()) {
            logger.info("同步TMS_ORDER表--->start");
        }
        wmsWarehouseNoticeExtMapper.updateSetMaxSQLPacket();
        int count = wmsWarehouseNoticeExtMapper.countTmsOrder();
        int cy = count / 500;
        int de = count % 500;
        HashMap<String, Object> params = Maps.newHashMap();
        if (cy > 0) {
            for (int n = 0; n < cy; n++) {
                int start = n * 500;
                int end = 500;
                params.put("start", start);
                params.put("end", end);
                List<WmsTmsOrder> tmsOrders = wmsWarehouseNoticeExtMapper.selectWmsTmsOrderListForSync(params);
                sysncTmsOrder(tmsOrders);
                if (n == cy - 1) {
                    start = cy * 500;
                    end = de;
                    params.put("start", start);
                    params.put("end", end);
                    List<WmsTmsOrder> lastTemps = wmsWarehouseNoticeExtMapper.selectWmsTmsOrderListForSync(params);
                    sysncTmsOrder(lastTemps);
                }
            }
        } else {
            int start = 0;
            params.put("start", start);
            params.put("end", de);
            List<WmsTmsOrder> temps = wmsWarehouseNoticeExtMapper.selectWmsTmsOrderListForSync(params);
            sysncTmsOrder(temps);
        }
        // 更新order 表中的对应 odcode
        wmsWarehouseNoticeExtMapper.updateOdCodeForSync();


        // --test --
        //HashMap<String, Object> params = Maps.newHashMap();
        //int start = 0;
        //int end = 5;
        //params.put("start", start);
        //params.put("end", end);
        //List<WmsAsnTemp> temps = wmsWarehouseNoticeExtMapper.selectWmsAsnTempListForSync(params);
        //sysncTemps(temps);
    }

    private void sysncTmsOrder(List<WmsTmsOrder> tmsOrders) {
        if (CollectionUtils.isNotEmpty(tmsOrders)) {
            ArrayList<WmsWarehouseNoticeHead> insertHeads = Lists.newArrayList();
            ArrayList<WmsWarehouseNoticeDetail> insertDetails = Lists.newArrayList();
            tmsOrders.forEach(v -> {
                WmsWarehouseNoticeHead head = new WmsWarehouseNoticeHead();
                WmsWarehouseNoticeDetail detail = new WmsWarehouseNoticeDetail();
                //补全其他字段 -detail
                detail.setWndWarehouseCode(v.getOdWhCode());
                detail.setWndCreate(v.getGmtCreate());
                detail.setWndUpdate(v.getGmtUpdate());
                detail.setWndSendBusinessFlag(String.valueOf(v.getSendBusinessFlag()));
                detail.setWndDataStatus(String.valueOf(v.getIsDeleted()));
                detail.setWndTransferFlag(v.getOddStockTransfer());
                detail.setWndBusinessType(InboundOrderBusinessTypeEnum.Z1.getCode());
                detail.setWndCreateUserName(v.getCreateName());
                detail.setWndUpdateUserName(v.getModifyName());
                detail.setWndVin(v.getOddVin());
                detail.setWndVehicleName(v.getOddVehicleSpecName());
                detail.setWndVehicleCode(v.getOddVehicleSpecName());
                detail.setWndVehicleDesc(v.getOddVehicleSpecDesc());
                detail.setWndCustomerWhno(v.getFactoryWhno());
                detail.setWndModifyType(v.getOdStatus());
                detail.setWndVehicleId(v.getOdStyleId());
                detail.setWndBusinessStatus(WmsBusinessStatusEnum.WND_NOT_RECEIVE.getCode());
                //head
                head.setWnhId(Long.valueOf("10000" + String.valueOf(v.getId())));
                head.setWnhCustomerCode(WmsCustomerEnum.CQ_JL.getCode());
                head.setWnhCustomerName(WmsCustomerEnum.CQ_JL.getName());
                head.setWnhWarehouseCode(v.getOdWhCode());
                head.setWnhDataStatus(String.valueOf(v.getIsDeleted()));
                head.setWnhSysSource(v.getCreateName());
                head.setWnhBusinessStatus(WmsBusinessStatusEnum.WNH_NOT_INBOUND.getCode());
                head.setWnhDataTimestamp(v.getFetchTimestamp());
                head.setWnhCreate(v.getGmtCreate());
                head.setWnhUpdate(v.getGmtUpdate());
                head.setWnhUnlcnOrderNo(v.getOdOrderno());
                head.setWnhCustomerOrderNo(v.getOdCustomerOrderNo());
                head.setWnhCustomerWaybillNo(v.getOdWaybillNo());
                head.setWnhOriginCode(v.getOdOriginCode());
                head.setWnhOriginName(v.getOdOrigin());
                head.setWnhDestinationCode(v.getOdDestCode());
                head.setWnhDestinationName(v.getOdDest());
                head.setWnhDataTimestamp(v.getFetchTimestamp());
                head.setWnhInboundNum(1);
                head.setWnhCreateUserName(v.getCreateName());
                head.setWnhUpdateUserName(v.getModifyName());
                //关联
                detail.setWndHeadId(head.getWnhId());
                insertHeads.add(head);
                insertDetails.add(detail);
            });
            wmsWarehouseNoticeExtMapper.insertHeadBatch(insertHeads);
            wmsWarehouseNoticeExtMapper.insertDetailBatch(insertDetails);
        }

    }

    private void sysncTemps(List<WmsAsnTemp> temps) {
        if (CollectionUtils.isNotEmpty(temps)) {
            ArrayList<WmsWarehouseNoticeHead> insertHeads = Lists.newArrayList();
            ArrayList<WmsWarehouseNoticeDetail> insertDetails = Lists.newArrayList();
            temps.forEach(v -> {
                WmsWarehouseNoticeHead head = new WmsWarehouseNoticeHead();
                WmsWarehouseNoticeDetail detail = new WmsWarehouseNoticeDetail();
                //重复校验
                WmsWarehouseNoticeDetailExample detailExample = new WmsWarehouseNoticeDetailExample();
                detailExample.createCriteria().andWndVinEqualTo(v.getAtVin())
                        .andWndDataStatusEqualTo(String.valueOf(DeleteFlagEnum.NORMAL.getValue()))
                        .andWndBusinessTypeEqualTo(InboundOrderBusinessTypeEnum.Z1.getCode());
                int i = wmsWarehouseNoticeDetailMapper.countByExample(detailExample);
                if (i > 0) {
                    throw new BusinessException("该车架号:" + detail.getWndVin() + "已经存在,无需重复导入");
                }
                //补全其他字段 -detail
                detail.setWndWarehouseCode(v.getWhcode());
                detail.setWndCreate(v.getGmtCreate());
                detail.setWndUpdate(v.getGmtUpdate());
                detail.setWndSendBusinessFlag(v.getAtSendBusinessFlag());
                detail.setWndDataStatus(String.valueOf(DeleteFlagEnum.NORMAL.getValue()));
                detail.setWndTransferFlag(WmsInboundOrderStockTransferEnum.STOCK_NORMAL.getCode());
                detail.setWndBusinessType(InboundOrderBusinessTypeEnum.Z1.getCode());
                detail.setWndCreateUserName(WmsSysSourceEnum.IMPORT.getValue());
                detail.setWndUpdateUserName(WmsSysSourceEnum.IMPORT.getValue());
                detail.setWndVin(v.getAtVin());
                detail.setWndVehicleName(v.getAtVehicleName());
                detail.setWndVehicleCode(v.getAtVehicleName());
                detail.setWndProducteTime(v.getAtProductionDate());
                detail.setWndOfflineTime(v.getAtOfflineDate());
                detail.setWndGearBoxNo(v.getAtGearboxNumber());
                detail.setWndCertification(v.getAtCertification());
                detail.setWndEngineNo(v.getAtEngineNumber());
                detail.setWndColorName(v.getAtCarColour());
                detail.setWndColorCode(v.getAtCarColourCode());
                detail.setWndMaterialCode(v.getAtMaterialCode());
                detail.setWndMaterialName(v.getAtMaterialName());
                detail.setWndBusinessStatus(WmsBusinessStatusEnum.WND_NOT_RECEIVE.getCode());
                detail.setWndId(v.getAtId());
                //head
                head.setWnhId(v.getAtId());
                head.setWnhCustomerCode(WmsCustomerEnum.JM.getCode());
                head.setWnhCustomerName(WmsCustomerEnum.JM.getName());
                head.setWnhWarehouseCode(v.getWhcode());
                head.setWnhDataStatus(String.valueOf(DeleteFlagEnum.NORMAL.getValue()));
                head.setWnhBatchNo(v.getAtBatchNo());
                head.setWnhSysSource(WmsSysSourceEnum.IMPORT.getValue());
                head.setWnhBusinessStatus(WmsBusinessStatusEnum.WNH_NOT_INBOUND.getCode());
                head.setWnhDataTimestamp(Long.valueOf(DateUtils.getStringFromDate(new Date(), DateUtils.FORMAT_DATETIME_NO_SEPARATOR)));
                head.setWnhCreate(v.getGmtCreate());
                head.setWnhUpdate(v.getGmtUpdate());
                head.setWnhUnlcnOrderNo(v.getAtOrderNo());
                head.setWnhInboundNum(1);
                head.setWnhCreateUserName(WmsSysSourceEnum.IMPORT.getValue());
                head.setWnhUpdateUserName(WmsSysSourceEnum.IMPORT.getValue());
                //关联
                detail.setWndHeadId(head.getWnhId());
                insertHeads.add(head);
                insertDetails.add(detail);
            });
            wmsWarehouseNoticeExtMapper.insertHeadBatch(insertHeads);
            wmsWarehouseNoticeExtMapper.insertDetailBatch(insertDetails);
        }
    }


    /**
     * 第一次调用接口失败的再继续调用5次--DCS
     */
    @Override
    public void updateOutOfStorageExcpForDcs() throws Exception {
        logger.info("WmsJMInboundServiceImpl.updateOutOfStorageDcs param.{}");
        //查询出入库异常表中为发送异常的数据及次数<=5的(最终状态为空的数据)
        WmsOutOfStorageExcpExample excpExample = new WmsOutOfStorageExcpExample();
        excpExample.createCriteria()
                .andDcsSendStatusNotEqualTo(SendStatusEnum.SEND_SUCCESS.getValue())
                .andDcsFinalStatusIsNull();
        excpExample.setOrderByClause("DATA_ID asc");
        excpExample.setLimitStart(0);
        excpExample.setLimitEnd(5);
        List<WmsOutOfStorageExcp> excps = wmsOutOfStorageExcpMapper.selectByExample(excpExample);
        if (CollectionUtils.isNotEmpty(excps)) {
            //执行调用接口
            ArrayList<WmsOutOfStorage> sendData = Lists.newArrayList();
            excps.forEach(v -> {
                WmsOutOfStorage wmsOutOfStorage = new WmsOutOfStorage();
                BeanUtils.copyProperties(v, wmsOutOfStorage);
                sendData.add(wmsOutOfStorage);
            });
            wmsJmDcsService.updateSendInOrOutboundRequest(sendData);
        }
    }


    /**
     * 第一次调用接口失败的再继续调用5次 --SAP
     */
    @Override
    public void updateOutOfStorageExcpForSap() throws Exception {
        logger.info("WmsJMInboundServiceImpl.updateOutOfStorageDcs param.{}");
        //查询出入库异常表中为发送异常的数据及次数<=5的(最终状态为空的数据)
        WmsOutOfStorageExcpExample excpExample = new WmsOutOfStorageExcpExample();
        excpExample.createCriteria()
                .andSendStatusSapNotEqualTo(SendStatusEnum.SEND_SUCCESS.getValue())
                .andSapFinalStatusIsNull();
        excpExample.setOrderByClause("DATA_ID asc");
        excpExample.setLimitStart(0);
        excpExample.setLimitEnd(5);
        List<WmsOutOfStorageExcp> excps = wmsOutOfStorageExcpMapper.selectByExample(excpExample);
        if (CollectionUtils.isNotEmpty(excps)) {
            //执行调用接口
            ArrayList<WmsOutOfStorage> sendData = Lists.newArrayList();
            excps.forEach(v -> {
                WmsOutOfStorage wmsOutOfStorage = new WmsOutOfStorage();
                BeanUtils.copyProperties(v, wmsOutOfStorage);
                sendData.add(wmsOutOfStorage);
            });
            wmsJmSapService.updateSendInOrOutbounRequest(sendData);
        }
    }
}
